<template>
    <view class="content">
        <view class="container">
            <!-- 输入框 -->
			<input class="post-txt" v-model="form.title" placeholder="请输入标题" type="text" />
            <textarea placeholder="想说什么就说什么叭- -" @blur="inputBlur" :focus="inputFocus" :auto-height="true"
                :show-confirm-bar="false" maxlength="1500" v-model="form.comment" class="post-txt"></textarea>

            <!-- 上传图片or视频 -->
            <view class="img-list">
                <view class="fffsss">
					<view v-for="(item, index) in form.imageList" :key='index' class="img-list-box">
					    <image :src="item" class="img-item" @tap="imgTypeSelect(item)"></image>
					</view>
				</view>
                <div @click="getChooseImage" class="addImg">
                    ➕
                </div>
            </view>
        </view>
        <!-- 选择板块 -->

        <!-- 底部确定按钮 -->
        <view @click="clickCreate" class="yue-base-button">
            <view>确定发布~</view>
        </view>
    </view>
</template>
<script>
export default {
    data() {
        return {
            // 默认输入框获得焦点
            inputFocus: true,
            form: {
				title: '',
                comment: '',
                imageList: [],
            },
        }
    },

    methods: {
        // 选择媒体类型
        selectType() {
            let that = this
            let itemL = ['拍照', '从相册选择照片']
            uni.showActionSheet({
                itemList: itemL,
                success: function (res) {
                    if (res.tapIndex == 0) {
                        uni.chooseImage({
                            sourceType: ['camera'], // 拍照选择
                            success: function (res) {
                                that.form.imageList.push(res.tempFilePaths)
                            }
                        });
                    }
                    if (res.tapIndex == 1) {
                        uni.chooseImage({
                            count: 9 - that.form.imageList.length,
                            sourceType: ['album'], //从相册选择
                            success: function (res) {
                                res.tempFilePaths.forEach(path => {
                                    that.form.imageList.push(path);
                                    // 发给oss 待写
                                })
                            }
                        });
                    }
                }
            });
        },

        // 图片状态选择
        imgTypeSelect(item) {
            let that = this
            uni.showActionSheet({
                itemList: ['预览', '删除'],
                success: function (res) {
                    if (res.tapIndex == 0) {
                        uni.previewImage({
                            current: item,
                            urls: that.form.imageList
                        })
                    }
                    if (res.tapIndex == 1) {
                        let index = that.form.imageList.findIndex(url => url === item);
                        if (index !== -1) {
                            that.form.imageList.splice(index, 1);
                        }
                    }
                }
            });
        },

        // 文字内容
        inputBlur(event) {
            this.inputCursor = event.detail.cursor;
            this.inputFocus = false;
        },

		async getChooseImage () {
			const fileList = [];
			try {
				const res = await uni.chooseImage({
					count: 3,
				});
				console.log('resres', res)
				const arr = res[1]['tempFilePaths'].map((filePath) => {
					console.log('filePath', filePath)
					return new Promise(async (resolve, reject) => {
						uni.uploadFile({
						        url: this.$serverUrl + 'uploadImg',
						        name: 'file', // 服务端接收文件的字段名
						        header: {
									'token': uni.getStorageSync('token'),
						            // 'Content-Type': 'multipart/form-data', // 设置请求头为 FormData 格式
						        },
								filePath,
						        // formData: {
						        //   file: filePath,
						        // },
						        success: (res) => {
						          console.log('res', JSON.parse(res.data).data.url)
								  this.form.imageList.push(JSON.parse(res.data).data.url)
						        },
						        fail: (err) => {
						          uni.showToast({
						            title: '上传失败',
						            icon: 'none',
						          });
						        },
						      });
						// uni.request({
						// 	url: this.$serverUrl + '/uploadImg',
						// 	method: 'POST',
						// 	header: {
						// 		'token': uni.getStorageSync('token'),
						// 		'Content-Type': 'multipart/form-data',
						// 	},
						// 	filePath,
						// 	name: 'file',
						// 	success: (res) => {
								
						// 		console.log('1111111', res)
						// 	}
						// });
						/* const result = parseJson(dataUpload as unknown as string) as UploadFileResponse;
						const resultUrl = result.data;
						if (resultUrl) {
							resolve(resultUrl);
						} else {
							reject('err');
						} */

					});
				});
					const result = await Promise.all(arr);
					fileList.push(...result);
			} catch (error) {
					// if (error['errMsg'] !== 'chooseImage:fail cancel') showToast('上传失败，请重新上传！');
				}
				return fileList;
		},
        // 发布
        clickCreate() {
			// 创建一个 Date 对象
			const currentDate = new Date();
			// 获取年、月、日
			const currentYear = currentDate.getFullYear();
			const currentMonth = currentDate.getMonth() + 1; // 月份从0开始，需要加1
			const currentDay = currentDate.getDate();
			console.log(`当前日期：${currentYear}-0${currentMonth}-${currentDay < 10 ? '0' + currentDay : currentDay}`);
            console.log(this.form, uni.getStorageSync('userInfo').id);
            if (!this.form.title) {
                uni.showToast({
                    title: "请输入标题噢",
                    icon: "error"
                })
                return;
            }
			if (!this.form.comment) {
			    uni.showToast({
			        title: "请输入内容噢",
			        icon: "error"
			    })
			    return;
			}
			if (this.form.imageList.length === 0) {
			    uni.showToast({
			        title: "请上次图片噢",
			        icon: "error"
			    })
			    return;
			}
			const data = {
			  "comment": this.form.comment,
			  "dateTime": `${currentYear}-0${currentMonth}-${currentDay < 10 ? '0' + currentDay : currentDay}`,
			  "file": JSON.stringify(this.form.imageList),
			  "title": this.form.title,
			  "userId": uni.getStorageSync('userInfo').id
			}
			uni.request({
				url: this.$serverUrl + 'addPhotoCircle',
				method: 'POST',
				header: {
					//token
					'token': uni.getStorageSync('token'),
				},
				data: data,
				success: (res) => {
					console.log('res', res.data.code === 200)
					if (res.data.code === 200) {
						uni.showToast({
							title: '发布成功',
							duration: 1500,
						});
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/friendsCircle/friendsCircle'
							});
						}, 1500)
					} else {
						uni.showToast({
						    title: '发布失败',
						    duration: 1500,
						    icon: none
						});
					}
				},
				fail(error) {
					uni.showToast({
					    title: '发布失败',
					    duration: 1500,
					    icon: none
					});
				}
			});
        },
    }
}
</script>
<style lang="scss" scoped>
.addImg {
	margin-top: 30rpx;
    width: 100px;
    height: 100px;
    background: #ebe9e9;
    text-align: center;
    line-height: 100px;
}

.content {
    background: #ccc;
    height: 100vh;
    background-color: #FFFFFF;
    border-radius: 30upx 30upx 0upx 0upx;
}

.container {
    background: #fff;
    width: 100%;
    padding: 10px;
    // padding: 20rpx 40rpx;
    // overflow: hidden;
}

.post-txt {
    padding: 10px;
    width: 100%;
    // line-height: 1rpx;
}

/* 选择位置 */
.choose-location {
    display: inline-flex;
    align-items: center;
    background-color: #eee;
    font-size: 28rpx;
    border-radius: 100rpx;
    padding: 10rpx 20rpx;
    margin-left: 5rpx;
    line-height: 1;
    color: #616161;

    .txt {
        margin-left: 10rpx;
    }
}

.yue-base-button {
    position: fixed;
    display: flex;
    align-items: center;
    justify-content: center;
    bottom: 0;
    width: 100%;
    padding: 40rpx 0;
    z-index: 3;
}

.yue-base-button view {
    width: 560rpx;
    text-align: center;
    height: 96rpx;
    line-height: 96rpx;
    border-radius: 96rpx;
    font-size: 32rpx;
    font-weight: 400;
    color: #FFFFFF;
    background: #FF80AB;
}

// 相机icon
.icon-camera {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 210rpx;
    height: 210rpx;
    border-radius: 6rpx;
    margin: 5rpx 0rpx 0rpx 5rpx;
    background-color: #f4f5f7;
}

// 媒体列表
.img-list {
    // display: flex;
    // flex-wrap: wrap;
    margin-bottom: 20rpx;
}
.fffsss {
	width: 100%;
	display: flex;
	flex-wrap: wrap;
	flex-direction: row !important;
}

.img-list-box {
    // display: flex;
    // justify-content: center;
    // align-items: center;
    // position: relative;
	width: 23%;
	height: 160rpx;
	margin-right: 2%;
	image {
		width: 100%;
		height: 100%;
	}
}

.img-item {
    width: 210rpx;
    height: 210rpx;
    margin: 5rpx;
    border-radius: 6rpx
}
</style>


